﻿using Microsoft.Extensions.Options;
using System.Net;
using System.Net.Mail;

namespace Utils
{
    public class EmailHelper
    {
        private readonly MailOptions _mailOptions;

        public EmailHelper(IOptions<MailOptions> mailOptions)
        {
            _mailOptions = mailOptions.Value;
        }

        public bool SendVerificationCode(string toEmail, string code)
        {
            // 使用SMTP客户端发送验证码邮件
            using (SmtpClient client = new(_mailOptions.Smtp, _mailOptions.Port))
            {
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential(_mailOptions.FromEmail, _mailOptions.Password);
                client.EnableSsl = _mailOptions.UseSsl;

                // 创建邮件内容
                MailMessage mailMessage = new()
                {
                    From = new MailAddress(_mailOptions.FromEmail, _mailOptions.FromName),
                    Subject = "Verification Code",
                    Body = $"Your verification code is：{code}。{_mailOptions.Signature}"
                };
                mailMessage.To.Add(toEmail);

                // 发送邮件
                client.Send(mailMessage);
            }

            try
            {
                // 邮件发送成功则返回true
                Console.WriteLine("邮件发送成功");
                return true;
            }
            catch (Exception ex)
            {
                // 发送失败则输出异常信息并返回false
                Console.WriteLine("邮件发送失败：" + ex.Message);
                return false;
            }
        }

        public class MailOptions
        {
            // 邮件选项类，包含用于配置邮件发送的信息

            public string Smtp { get; set; } // SMTP 地址
            public int Port { get; set; } // 端口号
            public bool UseSsl { get; set; } // 是否使用SSL
            public string FromEmail { get; set; } // 发件人邮箱
            public string Password { get; set; } // 密码
            public string FromName { get; set; } // 发件人名称
            public string Signature { get; set; } // 签名
        }
    }
}